/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2021-02-26 16:57:25
 * @LastEditors: ding-cx
 * @LastEditTime: 2021-03-19 16:52:23
 * @Description: 自定义权限的列表
 */
import { Application } from "egg";
import { DataTypes, Model } from "sequelize";
import { modelCommonField } from "../../utils";

export interface permissionListInterface extends Model {
  /** 所属菜单id */
  menu_id: number;
  /** 权限类型 */
  type: number;
  /** 权限名称 */
  cname: string;
  /** 授权标识 */
  ename: string;
  /** 创建者id */
  create_user_id: number;

  /** 修改者id */
  edit_user_id: number;
}

export default (app: Application) => {
  const model = app.model.define<permissionListInterface>(
    app.config.dbModel_prefix + "permission_list",
    {
      menu_id: {
        field: "menu_id",
        comment: "所属菜单id",
        type: DataTypes.INTEGER,
      },

      cname: {
        field: "cname",
        comment: "权限名称",
        type: DataTypes.STRING(20),
      },
      ename: {
        field: "ename",
        comment: "授权标识", //英文授权名称，比数字id更易懂。
        type: DataTypes.STRING(80),
      },
      ...modelCommonField,
    }
  );

  (model as any).associate = () => {
    model.belongsTo(app.model.Sys.Menus, {
      foreignKey: "menu_id",
      as: "menu_perm",
      constraints: false,
    });
  };

  model.findOrCreate({
    defaults: {
      menu_id: 5,
      cname: "角色批量授权",
      ename: "sys:role:batchPerm",
    },
    where: {
      ename: "sys:role:batchPerm",
    },
  });

  return model;
};
